<template>
  <div class="treatModify">
    <div class="header" style="font-size: 18px">
      <div class="line"></div>
      编辑服务信息
    </div>
    <div class="line2"></div>
    <div class="title">居民信息</div>
    <el-form ref="ruleFormRef" :rules="rules" :model="treatInfo" label-width="80px" class="demo-ruleForm" size="large"
      status-icon v-if="flag">
      <template style="display: flex">
        <el-form-item label="姓名" prop="resident.name">
          <el-input v-model="treatInfo.resident.name" style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="身份证号" prop="resident.IDCard">
          <el-input v-model="treatInfo.resident.IDCard" style="width: 200px" />
        </el-form-item>
        <el-form-item label="性别" prop="resident.gender">
          <el-select v-model="treatInfo.resident.gender" style="width: 200px">
            <el-option label="男" :value="0" />
            <el-option label="女" :value="1" />
          </el-select>
        </el-form-item>
      </template>
      <template style="display: flex">
        <el-form-item label="出生年月" prop="resident.birthday">
          <el-date-picker v-model="treatInfo.resident.birthday" type="date" label="Pick a date" placeholder="Pick a date"
            style="width: 200px" />
        </el-form-item>
        <el-form-item label="联系电话" prop="resident.tel">
          <el-input v-model="treatInfo.resident.tel" style="width: 200px" />
        </el-form-item>
        <el-form-item label="现居地" prop="resident.address">
          <el-input v-model="treatInfo.resident.address" style="width: 300px" />
        </el-form-item>
      </template>
      <el-form-item label="居民标签" prop="arr">
        <el-select v-model="arr" multiple placeholder="请选择" :clearable="true">
          <el-option :label="item.name" :value="item.id" v-for="(item, index) in LabelInfo" :key="index" />
        </el-select>
      </el-form-item>
      <el-form-item label="家庭成员" prop="desc">
        <template style="display: flex">
          <el-card shadow="hover">
            <template style="display: flex; justify-content: space-between">
              <img
                src="https://cdn7.axureshop.com/demo/1881228/images/%E5%BE%85%E5%AE%A1%E6%A0%B8%E7%AD%BE%E7%BA%A6%E8%AF%A6%E6%83%85/u1575.jpg"
                alt="" />
              <div class="info">
                <p style="margin-top: -10px">
                  <span>{{ emergency.emergencyContact }}</span>
                </p>
                <p style="margin-top: -15px">
                  {{ emergency.emergencyNumber }}
                </p>
              </div>
              <img
                src="https://cdn7.axureshop.com/demo/1881228/images/%E5%BE%85%E5%AE%A1%E6%A0%B8%E7%AD%BE%E7%BA%A6%E8%AF%A6%E6%83%85/u1576.png"
                alt="" />
            </template>
          </el-card>
        </template>
      </el-form-item>
    </el-form>
    <el-form ref="ruleFormRef" :model="resident" :rules="rule" label-width="80px" class="demo-ruleForm" size="large"
      status-icon v-else>
      <template style="display: flex">
        <el-form-item label="姓名" prop="name">
          <el-select v-model="resident.name" style="width: 200px" @change="userChange">
            <el-option :label="item.name" :value="item.id" v-for="(item, index) in userList" :key="index">
              <template #default>
                {{ item.name }}
                <span style="font-size: 12px; color: #999">
                  <span style="margin: 0 5px">{{
                    item.gender == 0 ? "男" : "女"
                  }}</span>
                  {{
                    new Date().getFullYear() -
                    Number(item.birthday.slice(0, 4))
                  }}岁
                </span>
              </template>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="IDCard">
          <el-input v-model="resident.IDCard" style="width: 200px" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="resident.gender" style="width: 200px" :disabled="disabled">
            <el-option label="男" :value="0" />
            <el-option label="女" :value="1" />
          </el-select>
        </el-form-item>
      </template>
      <template style="display: flex">
        <el-form-item label="出生年月" prop="birthday">
          <el-date-picker v-model="resident.birthday" type="date" label="Pick a date" placeholder="Pick a date"
            style="width: 200px" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="联系电话" prop="tel">
          <el-input v-model="resident.tel" style="width: 200px" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="现居地" prop="address">
          <el-input v-model="resident.address" style="width: 300px" :disabled="disabled" />
        </el-form-item>
      </template>
      <el-form-item label="居民标签" prop="arr">
        <el-select v-model="arr" multiple placeholder="请选择" :clearable="true" :disabled="disabled">
          <el-option :label="item.name" :value="item.id" v-for="(item, index) in LabelInfo" :key="index" />
        </el-select>
      </el-form-item>
      <el-form-item label="家庭成员" prop="desc">
        <template style="display: flex">
          <el-card shadow="hover">
            <template style="display: flex; justify-content: space-between">
              <img
                src="https://cdn7.axureshop.com/demo/1881228/images/%E5%BE%85%E5%AE%A1%E6%A0%B8%E7%AD%BE%E7%BA%A6%E8%AF%A6%E6%83%85/u1575.jpg"
                alt="" />
              <div class="info">
                <p style="margin-top: -10px">
                  <span>{{ emergency.emergencyContact }}</span>
                </p>
                <p style="margin-top: -15px">
                  {{ emergency.emergencyNumber }}
                </p>
              </div>
              <img
                src="https://cdn7.axureshop.com/demo/1881228/images/%E5%BE%85%E5%AE%A1%E6%A0%B8%E7%AD%BE%E7%BA%A6%E8%AF%A6%E6%83%85/u1576.png"
                alt="" />
            </template>
          </el-card>
        </template>
      </el-form-item>
    </el-form>
    <div class="line2"></div>
    <div class="title">服务信息</div>
    <el-form ref="ruleFormRef" :model="treatInfo" :rules="rules" label-width="80px" class="demo-ruleForm" size="large"
      status-icon>
      <template style="display: flex">
        <el-form-item label="服务编号" prop="number">
          <div style="width: 200px">{{ treatInfo.number }}</div>
        </el-form-item>
        <el-form-item label="服务机构" prop="organId">
          <el-select placeholder="请选择" v-model="treatInfo.organId" @change="organIdChange" style="width: 200px">
            <el-option :label="item.name" :value="item.id" v-for="(item, index) in agencyOrgan" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务团队" prop="teamId">
          <el-select placeholder="请选择" v-model="treatInfo.teamId" @change="serviceBasicChange" style="width: 200px">
            <el-option :label="item.name" :value="item.id" v-for="(item, index) in TeamList" :key="index" />
          </el-select>
        </el-form-item>
      </template>
      <template style="display: flex">
        <el-form-item label="服务医生" prop="doctorId">
          <el-select placeholder="请选择" v-model="treatInfo.doctorId" style="width: 200px">
            <el-option :label="item.name" :value="item.id" v-for="(item, index) in BasicDoctorList" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务包" prop="serviceId">
          <el-select placeholder="请选择" v-model="treatInfo.serviceId" style="width: 200px" @change="serviceIdChange">
            <el-option :label="item.name" :value="item.id" v-for="(item, index) in ServiceBasicList" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务项目" prop="serviceItemId">
          <el-select placeholder="请选择" v-model="treatInfo.serviceItemId" style="width: 200px">
            <el-option :label="item.name" :value="item.id" v-for="(item, index) in serviceIdList" :key="index">
              <template #default>
                {{ item.name }}
                <span style="color: red; font-size: 13px; margin-left: 10px">剩余{{ item.count }}次</span>
              </template></el-option>
          </el-select>
        </el-form-item>
      </template>
      <template style="display: flex">
        <el-form-item label="服务地点" prop="address">
          <el-select placeholder="请选择" v-model="treatInfo.address" style="width: 200px">
            <el-option label="签约人家中" :value="0" />
            <el-option label="机构门诊" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务时间" prop="appointmentTime">
          <el-date-picker v-model="treatInfo.appointmentTime" type="date" label="Pick a date" placeholder="Pick a date"
            style="width: 200px" /></el-form-item>
      </template>
      <el-form-item label="服务备注" prop="notes">
        <el-input style="width: 600px; height: 120px" maxlength="300" placeholder="Please input" show-word-limit
          type="textarea" v-model="treatInfo.notes" /></el-form-item>
      <el-button type="primary" @click="play(ruleFormRef)">保存</el-button>
      <el-button @click="Return">返回</el-button>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { type FormInstance, type FormRules, ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import api from "@/api";
import sj from "@/utils/yzy/sj";
const router = useRoute();
const routerr = useRouter();
//add or modify
const flag = ref(true);
//新增时用户信息
const resident = ref({
  name: "",
  IDCard: "",
  gender: "",
  birthday: "",
  tel: "",
  address: "",
});
//新增时封锁表单
const disabled = ref(false);
//所有居民信息
const userList = ref([
  { name: "数据", id: "没有", gender: 0, birthday: "姚泽宇" },
]);
//信息列表
const treatInfo = ref({
  id: "",
  number:
    Math.floor(Math.random() * (3000000000 - 2000000000 + 1)) + 2000000000,
  residentId: "",
  organId: "",
  teamId: "",
  doctorId: "",
  serviceId: "",
  serviceItemId: "",
  address: "",
  appointmentTime: "",
  notes: "",
  submissionTime: "",
  status: 0,
  score: 5,
  flag: 0,
  auditTime: null,
  checkerId: null,
  finishTime: null,
  checker: "段宏",
  resident: {
    id: "be642f70-efd6-11ed-835e-65d5662cddew",
    number: "20215132258654",
    userId: "67e98bc0-ee1b-11ed-8459-c76f227cade2",
    name: "刘泽军",
    picture: "public/upload/7abee44758ef44082ff53c87f4703657.jpg",
    IDCard: "513777188109182111",
    tel: "17799992111",
    address: "陕西西安",
    district: "陕西西安",
    gender: 0,
    birthday: "1881-09-18",
    residenceId: "800868d0-b40e-11ed-a611-3bf04a4b0d9f",
    nativePlace: "陕西西安",
    residenceAddress: "陕西西安",
    nationId: "613c4ad0-dcc6-11ed-b712-5ffe7a78b424",
    educationId: "e4034120-46ef-11ed-bbf8-c15b55eb9015",
    maritalStatusId: "c78a2a20-b41f-11ed-a611-3bf04a4b0d91",
    career: "略",
    workUnit: "略",
    emergencyContact: "无",
    emergencyNumber: "无",
    expenseTypeId: "004505b0-b420-11ed-a611-3bf04a4b0d93",
    designatedMedicalUnits: "略",
    origin: "用户注册",
    status: 0,
    flag: 0,
    createTime: "2023-01-16 11:18:11",
    auditTime: null,
    labelArr: [],
  },
  other: {
    oname: "成都市武侯区望江路社区卫生服务中心",
    tname: "段宏团队",
    dname: "陈晓平",
    sname: "老人服务包",
    siname: "血常规检查",
    totalCount: 2,
    count: 1,
  },
});
//紧急联系人
const emergency = ref({
  emergencyNumber: "",
  emergencyContact: "",
});
//疾病列表
const LabelInfo = ref([
  {
    id: "67e98bc0-ee1b-11ed-8459-c717227ca877",
    name: "心脏病",
    cname: "段宏",
    lastModifyTime: "2023-05-09 16:35:12",
    flag: 0,
    number: 1,
  },
]);
//机构列表
const agencyOrgan = ref([
  {
    address: "四川省成都市武侯区致民东路8号",
    contactName: "李瑞",
    contactTel: "(028)85434379",
    description:
      "成都市武侯区望江路社区卫生服务中心是政府举办的公益性医疗机构。中心系四川省全科医学中心社区培训基地、华西医院全科医学基层实践基地，同时还是四川大学华西医院、四川省人民医院、成都市第二人民医院等医院的对口辅导和双向转诊单位。2018年被国家卫生计生委评为“全国优质服务示范社区卫生服务中心”。",
    flag: 0,
    id: "67e98bc0-ee1b-11ed-8459-c76f227ca777",
    name: "成都市武侯区望江路社区卫生服务中心1",
    number: "2023591753249",
    picture: "",
  },
]);
//团队列表
const TeamList = ref([
  {
    id: "88579930-ee50-11ed-8059-0ba99686esd1",
    number: "202359172987",
    name: "陈晓平团队",
    picture: "public/upload/u5598.png",
    organId: "67e98bc0-ee1b-11ed-8459-c76f227ca578",
    score: 5,
    shareCount: 0,
    status: 0,
    flag: 0,
  },
]);
//医生列表
const BasicDoctorList = ref([
  {
    id: "67e98bc0-ee1b-11ed-8459-c76f227ca999",
    name: "陈晓平1",
  },
]);
//服务包列表
const ServiceBasicList = ref([
  {
    id: "7909bde0-828b-11ed-a736-b1a95d18c716",
    name: "0~6岁儿童服务包",
    targetAudience: "0~6岁儿童",
    picture: "public/upload/u4827.png",
    labelArr: [
      {
        name: "儿童",
      },
    ],
  },
]);
//服务项列表
const serviceIdList = ref([
  {
    id: "d49f9cb0-5c07-11ed-9450-8f19ea84b625",
    name: "血常规检查1",
    count: 2,
    type: 1,
    price: 80,
    description: "检查血液成分。",
    flag: 0,
  },
  {
    id: "d49f9cb2-5c07-11ed-9450-8f19ea84b624",
    name: "小儿推拿1",
    count: 3,
    type: 1,
    price: 120,
    description: "小儿推拿一次。",
    flag: 0,
  },
]);
//表单校验
const rule = reactive<FormRules>({
  name: [{ required: true, message: "必须填写", trigger: "blur" }],
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  "resident.name": [
    { min: 2, max: 10, message: "姓名长度为 2 到 10 个字符", trigger: "blur" },
    { required: true, message: "必须填写", trigger: "blur" },
  ],
  "resident.IDCard": [
    { required: true, message: "必须填写", trigger: "blur" },
    {
      pattern: /^\d{17}[\dXx]$/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
  "resident.gender": [{ required: true, message: "必须填写", trigger: "blur" }],
  "resident.birthday": [
    { required: true, message: "必须填写", trigger: "blur" },
  ],
  " resident.tel": [
    { required: true, message: "必须填写", trigger: "blur" },
    {
      pattern: /^\d{17}[\dXx]$/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
  "resident.address": [
    { required: true, message: "必须填写", trigger: "blur" },
  ],
  arr: [{ required: true, message: "必须填写", trigger: "blur" }],
  organId: [{ required: true, message: "必须填写", trigger: "blur" }],
  teamId: [{ required: true, message: "必须填写", trigger: "blur" }],
  doctorId: [{ required: true, message: "必须填写", trigger: "blur" }],
  serviceId: [{ required: true, message: "必须填写", trigger: "blur" }],
  takingEffectTime: [{ required: true, message: "必须填写", trigger: "blur" }],
  notes: [{ required: true, message: "必须填写", trigger: "blur" }],
  address: [{ required: true, message: "必须填写", trigger: "blur" }],
  appointmentTime: [{ required: true, message: "必须填写", trigger: "blur" }],
  serviceItemId: [{ required: true, message: "必须填写", trigger: "blur" }],
});
//保存
const play = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      if (flag.value) {
        let result = await api.serve.updateChcsServicedetail({
          id: treatInfo.value.id,
          number: treatInfo.value.number,
          residentId: treatInfo.value.residentId,
          organId: treatInfo.value.organId,
          teamId: treatInfo.value.teamId,
          doctorId: treatInfo.value.doctorId,
          serviceId: treatInfo.value.serviceId,
          serviceItemId: treatInfo.value.serviceItemId,
          address: treatInfo.value.address,
          appointmentTime: treatInfo.value.appointmentTime,
          notes: treatInfo.value.notes,
          submissionTime: treatInfo.value.submissionTime,
          status: treatInfo.value.status,
          score: treatInfo.value.score,
          flag: treatInfo.value.flag,
          auditTime: treatInfo.value.auditTime,
          checkerId: treatInfo.value.checkerId,
          finishTime: treatInfo.value.finishTime,
        });
        if (result.data.code === 200) {
          ElMessage.success("修改成功");
          routerr.push("/home/serve/treat");
        }
      } else {
        console.log({
          residentId: resident.value.name,
          organId: treatInfo.value.organId,
          teamId: treatInfo.value.teamId,
          doctorId: treatInfo.value.doctorId,
          serviceId: treatInfo.value.serviceId,
          serviceItemId: treatInfo.value.serviceItemId,
          address: treatInfo.value.address,
          appointmentTime: treatInfo.value.appointmentTime,
          notes: treatInfo.value.notes,
        });

        let result = await api.serve.saveServiceDetail({
          residentId: resident.value.name,
          organId: treatInfo.value.organId,
          teamId: treatInfo.value.teamId,
          doctorId: treatInfo.value.doctorId,
          serviceId: treatInfo.value.serviceId,
          serviceItemId: treatInfo.value.serviceItemId,
          address: treatInfo.value.address,
          appointmentTime: sj(treatInfo.value.appointmentTime),
          notes: treatInfo.value.notes,
        });
        if (result.data.code === 200) {
          ElMessage.success("新增成功");
          routerr.push("/home/serve/treat");
        }
      }
    }
  });
};
//返回
const Return = () => {
  routerr.push("/home/serve/treat");
};
//签约机构更改
const organIdChange = () => {
  getTeamByOrganId(); //团队
  treatInfo.value.serviceId = "";
  treatInfo.value.teamId = "";
  treatInfo.value.doctorId = "";
  treatInfo.value.serviceItemId = "";
};
//医生团体更改
const serviceBasicChange = () => {
  getServiceBasic();
  getBasicDoctor();
  treatInfo.value.serviceId = "";
  treatInfo.value.doctorId = "";
  treatInfo.value.serviceItemId = "";
};
//服务包更改
const serviceIdChange = () => {
  getserviceId();
  treatInfo.value.serviceItemId = "";
};
//居民更改
const userChange = async () => {
  let result = await api.Agency.getResidentLabelHealth(resident.value.name);
  console.log(result);
  resident.value.IDCard = result.data.data.IDCard;
  resident.value.gender = result.data.data.gender;
  resident.value.birthday = result.data.data.birthday;
  resident.value.tel = result.data.data.tel;
  resident.value.address = result.data.data.address;
  arr.value = result.data.data.labelArr.map((item: any) => item.id);
  emergency.value.emergencyContact = result.data.data.emergencyContact;
  emergency.value.emergencyNumber = result.data.data.emergencyNumber;
  disabled.value = true;
};
//
const arr = ref();
//获取信息
const getTreatInfo = async () => {
  if (router.query.id) {
    flag.value = true;
    let result = await api.serve.getServiceDetail(router.query.id as string);
    let result1 = await api.Agency.getResidentLabelHealth(
      result.data.data.resident.id
    );
    treatInfo.value = result.data.data;
    // //标签信息
    arr.value = treatInfo.value.resident.labelArr.map((item: any) => item.id);
    treatInfo.value.teamId = "";
    treatInfo.value.doctorId = "";
    treatInfo.value.serviceId = "";
    treatInfo.value.serviceItemId = "";
    emergency.value.emergencyContact = result1.data.data.emergencyContact;
    emergency.value.emergencyNumber = result1.data.data.emergencyNumber;
  } else {
    flag.value = false;
    getResidentBySOTSL();
  }
};
//获取居民信息
const getResidentBySOTSL = async () => {
  let result = await api.serve.getResidentBySOTSL();
  userList.value = result.data.data.result;
};
//获取疾病列表
const getLabelBySearch = async () => {
  let result = await api.Agency.getLabelBySearchApi();
  LabelInfo.value = result.data.data.result;
};
//获取所有机构
const getAllChcsOrgan = async () => {
  let result = await api.Agency.getAllChcsOrganApi();
  agencyOrgan.value = result.data.data.rows;
};
//根据机构获取团队
const getTeamByOrganId = async () => {
  let result = await api.Agency.getTeamByOrganId(treatInfo.value.organId);
  TeamList.value = result.data.data;
};
//根据团队获取服务包
const getServiceBasic = async () => {
  let result = await api.Agency.getServiceBasicApi(treatInfo.value.teamId);
  ServiceBasicList.value = result.data.data;
};
//根据团队获取医生
const getBasicDoctor = async () => {
  let result = await api.Agency.getBasicDoctor(treatInfo.value.teamId);
  BasicDoctorList.value = result.data.data;
};
//根据服务包获取服务项
const getserviceId = async () => {
  let result = await api.serve.getServiceItemByServiceIdApi(
    treatInfo.value.serviceId
  );
  serviceIdList.value = result.data.data;
};
getTreatInfo();
getLabelBySearch(); //疾病列表
getAllChcsOrgan(); //机构
</script>

<style lang="scss">
.treatModify {
  width: 1150px;
  margin: auto;
  padding: 20px;
  box-sizing: border-box;
  background-color: white;

  .header {
    @include flex(none, center, none);

    .line {
      width: 6px;
      height: 20px;
      background-color: skyblue;
      border-radius: 5px;
      margin-right: 10px;
    }
  }

  .line2 {
    width: 100%;
    border-bottom: 1px solid #eee;
    margin: 20px 0;
  }

  .title {
    margin-bottom: 20px;
  }

  .el-form {
    .el-card {
      width: 200px;
      height: 84px;
      box-sizing: border-box;
      margin-right: 20px;
      color: #999999;

      .info {
        font-size: 12px;

        div {
          line-height: 24px;
        }

        span {
          font-size: 15px;
          color: rgba(0, 0, 0, 0.829);
          margin-right: 10px;
        }
      }

      img {
        width: 40px;
        height: 40px;
      }

      img:last-of-type {
        width: 10px;
        height: 15px;
        transform: rotate(330deg);
      }
    }

    .el-form-item__label {
      font-size: 13px;
      color: #999999;
    }

    .el-form-item {
      margin-right: 80px;

      .el-textarea__inner {
        height: 120px;
      }
    }
  }
}
</style>
